package com.example.demo.controller;

import com.example.demo.enity.Employee;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;

import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * webClient是webFlux 线程非阻塞的远程调用方式 相当于  restTemplate
 *
 */
@RestController
public class WebClientController {

   static List<Employee>  employeeList=new ArrayList<>();

    {

         employeeList.add(new Employee(1,30,"zhangsan"));
         employeeList.add(new Employee(2,10,"xiaom"));
         employeeList.add(new Employee(3,40,"yht"));
         employeeList.add(new Employee(4,50,"zc"));
         employeeList.add(new Employee(6,66,"gsw"));

    }

    @GetMapping("fndALL")
    public Flux<Employee> findAll(){
        return  Flux.range(1,5).map(val->{
             return    employeeList.stream().filter(employee -> val.equals(employee.getId())).findFirst().get();
        }).delayElements(Duration.ofMillis(1000));
    }

    @GetMapping("fndEmployee")
    public  Employee[] findEmployee(){
        try{
            Thread.sleep(5000);
        }finally {
            return employeeList.toArray(new Employee[5]);
        }

    }

    /**
     * restTemplate花费时间：5111
     *
     *  RestTemplate调用方式是同步阻塞的，当请求异步接口时候，会等待直到返回结果，所以花费时间更长。
     */
    @GetMapping("rest")
    public List<Employee> findWithRestTemplate(){
        long startTime=System.currentTimeMillis();
        RestTemplate  restTemplate=new RestTemplate();
        ResponseEntity<Employee[]>  responseEntity=restTemplate.getForEntity("http://localhost:8081/fndEmployee",Employee[].class);
        List<Employee> employees = Arrays.asList(responseEntity.getBody());
        long endTime = System.currentTimeMillis();
        System.out.println("restTemplate花费时间："+ (endTime-startTime));
        return employees;
    }

    /**
     *   webClient花费时间：18
     *  WebClient调用方式是异步非阻塞的，当请求异步接口时候，会生成一个线程，而主线程继续执行后面任务，当异步结果返回时候，再将结果响应到前台，所以这种方式
     *  效率更高。
     */

    @GetMapping("webflux")
    public Flux<Employee> findWithWebClient(){
        long startTime=System.currentTimeMillis();
        Flux<Employee> employeeFlux = WebClient.create("http://localhost:8081/fndEmployee")
                .get().retrieve().bodyToFlux(Employee.class);
        long endTime = System.currentTimeMillis();
        System.out.println("webClient花费时间："+ (endTime-startTime));
        return employeeFlux;
    }



}
